package com.freesun.shop.controller;

import com.freesun.shop.entity.Basket;
import com.freesun.shop.entity.User;
import com.freesun.shop.service.BasketService;
import com.freesun.shop.vo.BasketResultVo;
import com.freesun.shop.vo.ShopCartItem;
import com.freesun.shop.vo.ShopCartItemDiscount;
import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.shiro.SecurityUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@RestController
public class BasketController {

    @Reference(check = false)
    private BasketService basketService;

    @ApiOperation("查询购物车的商品")
    @PostMapping("/p/shopCart/info")
    public ResponseEntity<List<BasketResultVo>> basekInfo() {
        List<BasketResultVo> baskets = new ArrayList<>(1);
        ShopCartItemDiscount shopCartItemDiscount = new ShopCartItemDiscount();
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        List<ShopCartItem> shopCartItems = basketService.findByUser(user.getUserId());
        shopCartItemDiscount.setShopCartItems(shopCartItems);
        List<ShopCartItemDiscount> shopCartItemDiscounts = new ArrayList<>();
        shopCartItemDiscounts.add(shopCartItemDiscount);
        BasketResultVo basketResultVo = new BasketResultVo();
        basketResultVo.setShopCartItemDiscounts(shopCartItemDiscounts);
        baskets.add(basketResultVo);
        return ResponseEntity.ok(baskets);
    }

    @ApiOperation("查询用户购物车的产品数量")
    @GetMapping("/p/shopCart/prodCount")
    public ResponseEntity<Integer> getProdCount() {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        Integer count = basketService.getProdCountByUser(user.getUserId());
        return ResponseEntity.ok(count);
    }

    @ApiOperation("加入或者修改商品到购物车")
    @PostMapping("/p/shopCart/changeItem")
    public ResponseEntity<Void> changeItem(@RequestBody Basket basket) {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        basket.setUserId(user.getUserId());
        basketService.changeItem(basket);
        return ResponseEntity.ok().build();
    }

    @ApiOperation("删除购物车商品条目")
    @DeleteMapping("/p/shopCart/deleteItem")
    public ResponseEntity<Void> deleteItem(@RequestBody List<Long> ids) {
        basketService.removeByIds(ids);
        return ResponseEntity.ok().build();
    }
    @ApiOperation("计算商品的总价格")
    @PostMapping("/p/shopCart/totalPay")
    public ResponseEntity<BigDecimal> totalPay(@RequestBody List<Long> ids){
        BigDecimal bigDecimal  = basketService.getTotalPay(ids);
        return ResponseEntity.ok(bigDecimal);
    }

}
